﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ScriptEngine
{
    public class ScriptDataSource : ScriptEngine.IScriptDataSource
    {
        public Script Create(Script script)
        {
            using (ScriptEngineModelContainer ctx = new ScriptEngineModelContainer())
            {
                ctx.Scripts.AddObject(script);

                ctx.SaveChanges();

                return script;
            }
        }

        public List<Script> ReadAll()
        {
            using (ScriptEngineModelContainer ctx = new ScriptEngineModelContainer())
            {
                return (from s in ctx.Scripts select s).ToList();
            }
        }

        public Script Read(Script script)
        {
            using (ScriptEngineModelContainer ctx = new ScriptEngineModelContainer())
            {
                return (from s in ctx.Scripts 
                        where s.Id == script.Id
                        select s).FirstOrDefault();
            }
        }

        public void Update(Script script)
        {

            using (ScriptEngineModelContainer ctx = new ScriptEngineModelContainer())
            {
                ctx.Scripts.Attach(script);

                ctx.ObjectStateManager.ChangeObjectState(script, System.Data.EntityState.Modified);
                
                ctx.SaveChanges();
            }
        }

        public void Delete(Script script)
        {
            using (ScriptEngineModelContainer ctx = new ScriptEngineModelContainer())
            {
                ctx.Scripts.Attach(script);

                ctx.Scripts.DeleteObject(script);

                ctx.SaveChanges();
            }
        }
    }
}